package com.maigao.core.exception;

import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerCode {

    private static final Map<Integer, String> CODES = new ConcurrentHashMap<>();

    public static final ServerCode SUCCESS = asCode(0); // success
    public static final ServerCode NOT_LOGIN = asCode(-101); //未登录
    public static final ServerCode FORBIDDEN = asCode(-403); //访问权限不足
    public static final ServerCode TOKEN_ILLEGAL = asCode(-111); //csrf 校验失败
    public static final ServerCode NOT_FOUND = asCode(404); //未找到
    public static final ServerCode UNAUTHORIZED = asCode(-401); //未授权
    public static final ServerCode SERVER_ERROR = asCode(500); //未曾设想的道路
    public static final ServerCode BAD_REQUEST = asCode(-400); //请求参数异常
    public static final ServerCode TOO_MANY_REQUESTS = asCode(-429); //请求过快


    static {
        CODES.putAll(defaults());
    }

    private final int code;
    private final String message;

    private ServerCode(int code) {
        this(code, null);
    }

    private ServerCode(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        if (StringUtils.isEmpty(this.message)) {
            return CODES.getOrDefault(this.code, String.valueOf(this.code));
        }
        return this.message;
    }

    public static ServerCode create(int code, String message) {
        return new ServerCode(code, message);
    }

    public static ServerCode asCode(int code) {
        return new ServerCode(code);
    }

    public static void addCodes(Map<Integer, String> codes) {
        CODES.putAll(codes);
    }

    private static Map<Integer, String> defaults() {
        Map<Integer, String> codes = new HashMap<>();
        codes.put(SUCCESS.getCode(), "success");
        codes.put(NOT_LOGIN.getCode(), "未登录");
        codes.put(TOKEN_ILLEGAL.getCode(), "csrf 校验失败");
        codes.put(FORBIDDEN.getCode(), "访问权限不足");
        return Collections.unmodifiableMap(codes);
    }
}